/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Formularios;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author FRANCISCO
 */
public class productos extends javax.swing.JFrame {

    /**
     * Creates new form productos
     */
    public productos() {
        initComponents();
        this.setLocationRelativeTo(null);
        this.setResizable(false);
        txtnom.setEditable(false);
        txtpre.setEditable(false);
        txtsto.setEditable(false);
        btneli.setEnabled(false);
        btnmod.setEnabled(false);
        btnreg.setEnabled(false);
        
        
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btnbus = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        txtnom = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        txtpre = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        txtsto = new javax.swing.JTextField();
        btnreg = new javax.swing.JButton();
        btnmod = new javax.swing.JButton();
        btneli = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        grilla = new javax.swing.JTable();
        jLabel5 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("PRODUCTOS");
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        btnbus.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/Search-icon.png"))); // NOI18N
        btnbus.setText("BUSCAR");
        btnbus.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnbusActionPerformed(evt);
            }
        });
        getContentPane().add(btnbus, new org.netbeans.lib.awtextra.AbsoluteConstraints(260, 30, 100, 40));

        jLabel1.setForeground(new java.awt.Color(255, 255, 255));
        jLabel1.setText("NOMBRE");
        getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 50, -1, 23));
        getContentPane().add(txtnom, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 40, 130, 30));

        jLabel2.setForeground(new java.awt.Color(255, 255, 255));
        jLabel2.setText("PRECIO");
        getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 110, -1, -1));

        txtpre.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtpreKeyTyped(evt);
            }
        });
        getContentPane().add(txtpre, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 100, 140, 30));

        jLabel3.setForeground(new java.awt.Color(255, 255, 255));
        jLabel3.setText("STOCK");
        getContentPane().add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 170, -1, -1));

        txtsto.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtstoKeyTyped(evt);
            }
        });
        getContentPane().add(txtsto, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 160, 140, 30));

        btnreg.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/Actions-document-save-icon.png"))); // NOI18N
        btnreg.setText("REGISTRAR");
        btnreg.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnregActionPerformed(evt);
            }
        });
        getContentPane().add(btnreg, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 220, -1, -1));

        btnmod.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/refresh.png"))); // NOI18N
        btnmod.setText("MODIFICAR");
        btnmod.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnmodActionPerformed(evt);
            }
        });
        getContentPane().add(btnmod, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 220, -1, -1));

        btneli.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/delete.png"))); // NOI18N
        btneli.setText("ELIMINAR");
        btneli.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btneliActionPerformed(evt);
            }
        });
        getContentPane().add(btneli, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 220, -1, -1));

        jButton1.setText("salir");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(570, 410, -1, -1));

        grilla.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        grilla.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "NOMBRE", "PRECIO", "STOCK"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.Integer.class, java.lang.Integer.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(grilla);
        grilla.getColumnModel().getColumn(0).setResizable(false);
        grilla.getColumnModel().getColumn(1).setResizable(false);
        grilla.getColumnModel().getColumn(2).setResizable(false);

        getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 260, -1, 150));

        jLabel5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/energia_azul-1024x768.jpg"))); // NOI18N
        jLabel5.setText("jLabel5");
        getContentPane().add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, -10, 640, 450));

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
Plataforma pla = new Plataforma();
pla.setVisible(true);
dispose();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void btnregActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnregActionPerformed
        try {

            DriverManager.registerDriver(new org.gjt.mm.mysql.Driver());
            try (Connection conexion = DriverManager.getConnection("jdbc:mysql://localhost/pasteleria1211","root", "12345")) {
               
                Statement s = conexion.createStatement();

                s.execute("insert into producto values('"+txtnom.getText()+"','"+txtpre.getText()+"','"+txtsto.getText()+"');");
                JOptionPane.showMessageDialog(this,"PRODUCTO REGISTRADO","REGISTRO", 1);
               
            }
            }   catch (SQLException s) {
                      JOptionPane.showMessageDialog(null, s, "" + s, JOptionPane.ERROR_MESSAGE);
             }
        
        actualizartabla();
        
        txtnom.setText("");
        txtpre.setText("");
        txtsto.setText("");
    }//GEN-LAST:event_btnregActionPerformed

    private void btnmodActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnmodActionPerformed
   
        try {

            DriverManager.registerDriver(new org.gjt.mm.mysql.Driver());
            try (Connection conexion = DriverManager.getConnection("jdbc:mysql://localhost/pasteleria1211","root", "12345")) {
               
                Statement s = conexion.createStatement();

                s.execute("update producto set precio ='"+this.txtpre.getText()+"',stock ='"+txtsto.getText()+"' where producto.nombre='"+txtnom.getText()+"';");
                JOptionPane.showMessageDialog(this,"PRODUCTO MODIFICADO","MODIFICACION", 1);
               
            }
            }   catch (SQLException s) {
                      JOptionPane.showMessageDialog(null, s, "no se encontro al usuario" + s, JOptionPane.ERROR_MESSAGE);
             }
        
        actualizartabla();
                           txtnom.setText("");
        txtpre.setText("");
        txtsto.setText("");
    }//GEN-LAST:event_btnmodActionPerformed

    private void btneliActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btneliActionPerformed
       try {

            DriverManager.registerDriver(new org.gjt.mm.mysql.Driver());
            try (Connection conexion = DriverManager.getConnection("jdbc:mysql://localhost/pasteleria1211","root", "12345")) {
               
                Statement s = conexion.createStatement();
               s.execute("delete venta_producto from venta_producto where venta_producto.nombre_producto= '"+txtnom.getText()+"';");
                s.execute("delete producto from producto where producto.nombre= '"+txtnom.getText()+"';");
                JOptionPane.showMessageDialog(this,"PRODUCTO ELIMINADO", "ELIMINADO",1);
               
            }
            }   catch (SQLException s) {
                      JOptionPane.showMessageDialog(null, s, "" + s, JOptionPane.ERROR_MESSAGE);
             }
        
        actualizartabla();
                    txtnom.setText("");
        txtpre.setText("");
        txtsto.setText("");
                     
    }//GEN-LAST:event_btneliActionPerformed

    private void btnbusActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnbusActionPerformed
        try {

            DriverManager.registerDriver(new org.gjt.mm.mysql.Driver());
            try (Connection conexion = DriverManager.getConnection("jdbc:mysql://localhost/pasteleria1211","root", "12345")) {

                Statement s = conexion.createStatement();

                ResultSet rs = s.executeQuery("select nombre,precio,stock from producto where producto.nombre = '"+this.txtnom.getText()+"';");

                txtnom.setEditable(true);
                txtpre.setEditable(true);
                txtsto.setEditable(true);
                btneli.setEnabled(true);
                btnmod.setEnabled(true);
                btnreg.setEnabled(true);

                DefaultTableModel modelo = new DefaultTableModel();

                this.grilla.setModel(modelo);
                ResultSetMetaData rsMd = rs.getMetaData();
                int cantidadColumnas = rsMd.getColumnCount();

                for (int i = 1; i <= cantidadColumnas; i++) {
                    modelo.addColumn(rsMd.getColumnLabel(i));
                }

                while (rs.next()) {
                    Object[] fila = new Object[cantidadColumnas];
                    for (int j = 0; j < cantidadColumnas; j++) {
                        fila[j] = rs.getObject(j + 1);

                        if(j==1){
                            txtpre.setText(rs.getObject(j+1).toString());

                        }
                        if(j==2){
                            txtsto.setText(rs.getObject(j+1).toString());

                        }
                        System.out.println(j);
                    }
                    modelo.addRow(fila);
                }}
            }   catch (SQLException s) {
                JOptionPane.showMessageDialog(null, s, "no se encontro al usuario" + s, JOptionPane.ERROR_MESSAGE);
            }

            actualizartabla();
    }//GEN-LAST:event_btnbusActionPerformed

    private void txtpreKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtpreKeyTyped
      if(!Character.isDigit(evt.getKeyChar())){
   evt.consume();
        }
    }//GEN-LAST:event_txtpreKeyTyped

    private void txtstoKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtstoKeyTyped
       if(!Character.isDigit(evt.getKeyChar())){
    evt.consume();
      }
    }//GEN-LAST:event_txtstoKeyTyped

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(productos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(productos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(productos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(productos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new productos().setVisible(true);
            }
        });
    }
    
      public void actualizartabla(){
    try {
        

            DriverManager.registerDriver(new org.gjt.mm.mysql.Driver());
            try (Connection conexion = DriverManager.getConnection("jdbc:mysql://localhost/pasteleria1211","root", "12345")) {
               
                Statement s = conexion.createStatement();

                ResultSet rs = s.executeQuery("select * from producto");
                
               
              
            DefaultTableModel modelo = new DefaultTableModel();

            this.grilla.setModel(modelo);
            ResultSetMetaData rsMd = rs.getMetaData();
            int cantidadColumnas = rsMd.getColumnCount();
rs.getMetaData();
            for (int i = 1; i <= cantidadColumnas; i++) {
                modelo.addColumn(rsMd.getColumnLabel(i));
            }
            
            while (rs.next()) {
                Object[] fila = new Object[cantidadColumnas];
                for (int j = 0; j < cantidadColumnas; j++) {
                    fila[j] = rs.getObject(j + 1);
                    
                    
                   
                    
                        System.out.println(j);
                }
                modelo.addRow(fila);
            }
            } }  catch (SQLException s) {
                      JOptionPane.showMessageDialog(null, s, "no se encontro al usuario" + s, JOptionPane.ERROR_MESSAGE);
             }
    
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnbus;
    private javax.swing.JButton btneli;
    private javax.swing.JButton btnmod;
    private javax.swing.JButton btnreg;
    private javax.swing.JTable grilla;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField txtnom;
    private javax.swing.JTextField txtpre;
    private javax.swing.JTextField txtsto;
    // End of variables declaration//GEN-END:variables
}
